#include "profiles.h"
#include "ui_profiles.h"

#include <QInputDialog>
#include <QMessageBox>
#include <QStandardItemModel>
#include <QSettings>
#include <QDir>
#include <QtDebug>

Profiles::Profiles(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Profiles)
{
    ui->setupUi(this);

    ui->remove_toolButton->setDisabled(true);
    ui->number_spinBox->setDisabled(true);
    ui->cycle_spinBox->setDisabled(true);
    ui->frequency_spinBox->setDisabled(true);
    ui->pause_spinBox->setDisabled(true);
    ui->autorun_spinBox->setDisabled(true);


    model = new QStandardItemModel(ui->listView);
    ui->listView->setModel(model);

    this->load();

    connect(ui->add_toolButton, SIGNAL(clicked()), this, SLOT(add()));
    connect(ui->remove_toolButton, SIGNAL(clicked()), this, SLOT(remove()));
    connect(ui->listView, SIGNAL(clicked(QModelIndex)), this, SLOT(currentChanged(QModelIndex)));
    connect(ui->listView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(currentChanged(QModelIndex, QModelIndex)));

    this->selectProfile(qApp->property("currentprofile").toString());
}

Profiles::~Profiles()
{
    delete ui;
}

void Profiles::add()
{
    bool ok;
    QString text = QInputDialog::getText(this, tr("Add profile"),
                                              tr("Profile name:"), QLineEdit::Normal,
                                         "New profile", &ok);
    if (ok && !text.isEmpty()){
        QList<QStandardItem *> list = model->findItems(text, Qt::MatchExactly);
        if(list.size() > 0){
                QMessageBox msgBox;
                msgBox.setIcon(QMessageBox::Warning);
                msgBox.setText("Profile already exists with this name.");
                msgBox.exec();
                return;
        }
        QStandardItem* item = new QStandardItem(text);
        item->setData(8, 1001);
        item->setData(12, 1002);
        item->setData(800, 1003);
        item->setData(3000, 1004);
        model->appendRow(item);
    }

}

void Profiles::remove()
{
    if(!ui->listView->selectionModel()->currentIndex().isValid()) return;

    QStandardItem* item = model->itemFromIndex(ui->listView->selectionModel()->currentIndex());
    int ret = QMessageBox::question(this, tr("Profiles"),
                                tr("Do you want to delete %1?\nThis could not be restored!")
                                .arg(item->text()),
                                QMessageBox::Ok | QMessageBox::Cancel);
    if(ret == QMessageBox::Cancel) return;
    model->removeRow(item->row());
}

void Profiles::load()
{
    QDir appdir = QDir::home();
    QSettings settings(appdir.filePath("Breath.ini"), QSettings::IniFormat);
    settings.beginGroup("Profiles");
    QStringList list = settings.childGroups();
    for (int i = 0; i < list.size(); ++i){
        QStandardItem* item = new QStandardItem(list.at(i));
        settings.beginGroup(list.at(i));
        item->setData(settings.value("Numbers", 8).toInt(), 1001);
        item->setData(settings.value("Cycles", 12).toInt(), 1002);
        item->setData(settings.value("Frequency", 800).toInt(), 1003);
        item->setData(settings.value("Pause", 3000).toInt(), 1004);
        model->appendRow(item);
        settings.endGroup();
    }
    settings.endGroup();
    settings.beginGroup("Program");
    ui->startbeep_checkBox->setChecked(settings.value("StartBeep", true).toBool());
    ui->endbeep_checkBox->setChecked(settings.value("EndBeep", true).toBool());
    ui->autorun_checkBox->setChecked(settings.value("AutoStart", false).toBool());
    ui->autorun_spinBox->setValue(settings.value("AutoStartSeconds", 10).toInt());
    settings.endGroup();
}

void Profiles::save()
{
    QDir appdir = QDir::home();
    QSettings settings(appdir.filePath("Breath.ini"), QSettings::IniFormat);
    settings.beginGroup("Profiles");
    settings.remove("");
    settings.endGroup();
    settings.beginGroup("Profiles");
    for(int i=0; i<model->rowCount(); ++i){
        QStandardItem* item = model->item(i);
        settings.beginGroup(item->text());
        settings.setValue("Numbers", item->data(1001).toInt());
        settings.setValue("Cycles", item->data(1002).toInt());
        settings.setValue("Frequency", item->data(1003).toInt());
        settings.setValue("Pause", item->data(1004).toInt());
        bool current = (item == model->itemFromIndex(ui->listView->selectionModel()->currentIndex()));
        settings.setValue("Current", current);
        settings.endGroup();
    }
    settings.endGroup();
    settings.beginGroup("Program");
    settings.setValue("StartBeep", ui->startbeep_checkBox->isChecked());
    settings.setValue("EndBeep", ui->endbeep_checkBox->isChecked());
    settings.setValue("AutoStart", ui->autorun_checkBox->isChecked());
    settings.setValue("AutoStartSeconds", ui->autorun_spinBox->value());
    settings.endGroup();
}

void Profiles::currentChanged(const QModelIndex &current)
{
    if(!current.isValid()) {
        ui->remove_toolButton->setDisabled(true);
        ui->number_spinBox->setDisabled(true);
        ui->cycle_spinBox->setDisabled(true);
        ui->frequency_spinBox->setDisabled(true);
        ui->pause_spinBox->setDisabled(true);
    }
    else {
        QStandardItem* item = model->itemFromIndex(current);
        qDebug() << item->text();
        ui->remove_toolButton->setDisabled(false);
        ui->number_spinBox->setDisabled(false);
        ui->cycle_spinBox->setDisabled(false);
        ui->frequency_spinBox->setDisabled(false);
        ui->pause_spinBox->setDisabled(false);
        ui->number_spinBox->disconnect();
        ui->cycle_spinBox->disconnect();
        ui->frequency_spinBox->disconnect();
        ui->pause_spinBox->disconnect();
        ui->number_spinBox->setValue(item->data(1001).toInt());
        ui->cycle_spinBox->setValue(item->data(1002).toInt());
        ui->frequency_spinBox->setValue(item->data(1003).toInt());
        ui->pause_spinBox->setValue(item->data(1004).toInt());
        connect(ui->number_spinBox, SIGNAL(valueChanged(int)), this, SLOT(paramChanged(int)));
        connect(ui->cycle_spinBox, SIGNAL(valueChanged(int)), this, SLOT(paramChanged(int)));
        connect(ui->frequency_spinBox, SIGNAL(valueChanged(int)), this, SLOT(paramChanged(int)));
        connect(ui->pause_spinBox, SIGNAL(valueChanged(int)), this, SLOT(paramChanged(int)));
    }
}

void Profiles::currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
    if(ui->listView->selectionModel()->isSelected(current)){
        this->currentChanged(current);
    }
}

void Profiles::paramChanged(int /*value*/)
{
    if(!ui->listView->selectionModel()->currentIndex().isValid()) return;
    QStandardItem* item = model->itemFromIndex(ui->listView->selectionModel()->currentIndex());
    item->setData(ui->number_spinBox->value(), 1001);
    item->setData(ui->cycle_spinBox->value(), 1002);
    item->setData(ui->frequency_spinBox->value(), 1003);
    item->setData(ui->pause_spinBox->value(), 1004);
}

void Profiles::accept()
{
    save();
    QDialog::accept();
}

void Profiles::selectProfile(const QString &profile)
{
    if(profile.isEmpty()) return;
    QList<QStandardItem *> list = model->findItems(profile, Qt::MatchExactly);
    if(list.size() > 0){
        const QModelIndex index = list.at(0)->index();
        ui->listView->selectionModel()->select(index, QItemSelectionModel::Select);
        ui->listView->scrollTo(index);
        this->currentChanged(index);
    }
}
